package com.chapter.sample.service.datasource;

import com.chapter.sample.answer.exporter.annotations.RedisCacheAnnotation;
import com.chapter.sample.entity.coupon.CouponEntity;
import com.chapter.sample.entity.member.MemberEntity;
import com.chapter.sample.service.CouponService;
import com.chapter.sample.service.MemberService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
public class DynamicDatasourceServiceImpl implements DynamicDatasourceService {
    @Autowired
    private CouponService couponService;

    @Autowired
    private MemberService memberService;

    @Override
    public void dynamicData() {
        List<MemberEntity> memberList = memberService.list();
        List<CouponEntity> couponList = couponService.list();
        log.info("member : {}", memberList);
        log.info("coupon : {}", couponList);
    }

    public static final String CACHE_KEY_MEMBER = "member:";

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public boolean addMember(MemberEntity memberEntity) {
        log.info("插入之前member:{}", memberEntity);
        //1、先往mysl插入记录
        boolean saveFlag = memberService.save(memberEntity);
        log.info("插入之后member:{}", memberEntity);
        log.info("================================");

        if (saveFlag) {
            //2、插入成功到数据库里面，重写捞出新数据出来，放入缓存
            memberEntity = memberService.getById(memberEntity.getId());
            //3、拼装缓存Key
            String key = CACHE_KEY_MEMBER + memberEntity.getId();
            //4、往MySQL里插入成功,随后再从MySQL查询出来，插入Redis
            redisTemplate.opsForValue().set(key, memberEntity);
        }
        return saveFlag;
    }

    /*@Override
    public MemberEntity getMemberById(Integer id) {
        MemberEntity member = null;
        //1、拼装缓存Key
        String key = CACHE_KEY_MEMBER + id;
        //2、查询redis
        member = (MemberEntity) redisTemplate.opsForValue().get(key);
        //3、redis无，近一步查询mysql
        if (member == null) {
            //3、1 从MySQL查询出Member
            member = memberService.getById(id);
            //3、2 mysql中无，redis无
            if (member != null) {
                //3、3把Mysql捞到的数据写入Redis，方便下次查询redis命中
                redisTemplate.opsForValue().set(key, member);
            }
        }
        //4、redis有，直接返回
        return member;
    }*/

    @Override
    @RedisCacheAnnotation(keyPrefix = "user",matchValve = "#id")
    public MemberEntity getMemberById(Integer id) {
        //3、1 从MySQL查询出Member
        return memberService.getById(id);
    }


}
